import "./mp-html-sfc.css";
import node from "./node/node";
import Parser from "./parser";
const plugins = [];
const dom = weex.requireModule("dom");
const __vue_sfc__ = {
  name: "mp-html",
  data() {
    return {
      nodes: [],
      // #ifdef APP-PLUS-NVUE
      height: 3
      // #endif
    };
  },
  props: {
    containerStyle: {
      type: String,
      default: ""
    },
    content: {
      type: String,
      default: ""
    },
    copyLink: {
      type: [Boolean, String],
      default: true
    },
    domain: String,
    errorImg: {
      type: String,
      default: ""
    },
    lazyLoad: {
      type: [Boolean, String],
      default: false
    },
    loadingImg: {
      type: String,
      default: ""
    },
    pauseVideo: {
      type: [Boolean, String],
      default: true
    },
    previewImg: {
      type: [Boolean, String],
      default: true
    },
    scrollTable: [Boolean, String],
    selectable: [Boolean, String],
    setTitle: {
      type: [Boolean, String],
      default: true
    },
    showImgMenu: {
      type: [Boolean, String],
      default: true
    },
    tagStyle: Object,
    useAnchor: [Boolean, Number]
  },
  // #ifdef VUE3
  emits: ["load", "ready", "imgtap", "linktap", "play", "error"],
  // #endif
  // #ifndef APP-PLUS-NVUE
  components: {
    node
  },
  // #endif
  watch: {
    content(content) {
      this.setContent(content);
    }
  },
  created() {
    this.plugins = [];
    for (let i = plugins.length; i--; ) {
      this.plugins.push(new plugins[i](this));
    }
  },
  mounted() {
    if (this.content && !this.nodes.length) {
      this.setContent(this.content);
    }
  },
  beforeDestroy() {
    this._hook("onDetached");
  },
  methods: {
    /**
     * @description 将锚点跳转的范围限定在一个 scroll-view 内
     * @param {Object} page scroll-view 所在页面的示例
     * @param {String} selector scroll-view 的选择器
     * @param {String} scrollTop scroll-view scroll-top 属性绑定的变量名
     */
    in(page, selector, scrollTop) {
      if (page && selector && scrollTop) {
        this._in = {
          page,
          selector,
          scrollTop
        };
      }
    },
    /**
     * @description 锚点跳转
     * @param {String} id 要跳转的锚点 id
     * @param {Number} offset 跳转位置的偏移量
     * @returns {Promise}
     */
    navigateTo(id, offset) {
      return new Promise((resolve, reject) => {
        if (!this.useAnchor) {
          reject(Error("Anchor is disabled"));
          return;
        }
        offset = offset || parseInt(this.useAnchor) || 0;
        if (!id) {
          dom.scrollToElement(this.$refs.web, {
            offset
          });
          resolve();
        } else {
          this._navigateTo = {
            resolve,
            reject,
            offset
          };
          this.$refs.web.evalJs('uni.postMessage({data:{action:"getOffset",offset:(document.getElementById(' + id + ")||{}).offsetTop}})");
        }
        let deep = " ";
        deep = ">>>";
        const selector = uni.createSelectorQuery().in(this._in ? this._in.page : this).select((this._in ? this._in.selector : "._root") + (id ? `${deep}#${id}` : "")).boundingClientRect();
        if (this._in) {
          selector.select(this._in.selector).scrollOffset().select(this._in.selector).boundingClientRect();
        } else {
          selector.selectViewport().scrollOffset();
        }
        selector.exec((res) => {
          if (!res[0]) {
            reject(Error("Label not found"));
            return;
          }
          const scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + offset;
          if (this._in) {
            this._in.page[this._in.scrollTop] = scrollTop;
          } else {
            uni.pageScrollTo({
              scrollTop,
              duration: 300
            });
          }
          resolve();
        });
      });
    },
    /**
     * @description 获取文本内容
     * @return {String}
     */
    getText(nodes) {
      let text = "";
      (function traversal(nodes2) {
        for (let i = 0; i < nodes2.length; i++) {
          const node2 = nodes2[i];
          if (node2.type === "text") {
            text += node2.text.replace(/&amp;/g, "&");
          } else if (node2.name === "br") {
            text += "\n";
          } else {
            const isBlock = node2.name === "p" || node2.name === "div" || node2.name === "tr" || node2.name === "li" || node2.name[0] === "h" && node2.name[1] > "0" && node2.name[1] < "7";
            if (isBlock && text && text[text.length - 1] !== "\n") {
              text += "\n";
            }
            if (node2.children) {
              traversal(node2.children);
            }
            if (isBlock && text[text.length - 1] !== "\n") {
              text += "\n";
            } else if (node2.name === "td" || node2.name === "th") {
              text += "	";
            }
          }
        }
      })(nodes || this.nodes);
      return text;
    },
    /**
     * @description 获取内容大小和位置
     * @return {Promise}
     */
    getRect() {
      return new Promise((resolve, reject) => {
        uni.createSelectorQuery().in(this).select("#_root").boundingClientRect().exec((res) => res[0] ? resolve(res[0]) : reject(Error("Root label not found")));
      });
    },
    /**
     * @description 暂停播放媒体
     */
    pauseMedia() {
      for (let i = (this._videos || []).length; i--; ) {
        this._videos[i].pause();
      }
      const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].pause()';
      let page = this.$parent;
      while (!page.$scope)
        page = page.$parent;
      page.$scope.$getAppWebview().evalJS(command);
      this.$refs.web.evalJs(command);
    },
    /**
     * @description 设置媒体播放速率
     * @param {Number} rate 播放速率
     */
    setPlaybackRate(rate) {
      this.playbackRate = rate;
      for (let i = (this._videos || []).length; i--; ) {
        this._videos[i].playbackRate(rate);
      }
      const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].playbackRate=' + rate;
      let page = this.$parent;
      while (!page.$scope)
        page = page.$parent;
      page.$scope.$getAppWebview().evalJS(command);
      this.$refs.web.evalJs(command);
    },
    /**
     * @description 设置内容
     * @param {String} content html 内容
     * @param {Boolean} append 是否在尾部追加
     */
    setContent(content, append) {
      if (!append || !this.imgList) {
        this.imgList = [];
      }
      const nodes = new Parser(this).parse(content);
      if (this._ready) {
        this._set(nodes, append);
      }
      this.$set(this, "nodes", append ? (this.nodes || []).concat(nodes) : nodes);
      this._videos = [];
      this.$nextTick(() => {
        this._hook("onLoad");
        this.$emit("load");
      });
      if (this.lazyLoad || this.imgList._unloadimgs < this.imgList.length / 2) {
        let height = 0;
        const callback = (rect) => {
          if (!rect || !rect.height)
            rect = {};
          if (rect.height === height) {
            this.$emit("ready", rect);
          } else {
            height = rect.height;
            setTimeout(() => {
              this.getRect().then(callback).catch(callback);
            }, 350);
          }
        };
        this.getRect().then(callback).catch(callback);
      } else {
        if (!this.imgList._unloadimgs) {
          this.getRect().then((rect) => {
            this.$emit("ready", rect);
          }).catch(() => {
            this.$emit("ready", {});
          });
        }
      }
    },
    /**
     * @description 调用插件钩子函数
     */
    _hook(name) {
      for (let i = plugins.length; i--; ) {
        if (this.plugins[i][name]) {
          this.plugins[i][name]();
        }
      }
    },
    // #ifdef APP-PLUS-NVUE
    /**
     * @description 设置内容
     */
    _set(nodes, append) {
      this.$refs.web.evalJs("setContent(" + JSON.stringify(nodes).replace(/%22/g, "") + "," + JSON.stringify([this.containerStyle.replace(/(?:margin|padding)[^;]+/g, ""), this.errorImg, this.loadingImg, this.pauseVideo, this.scrollTable, this.selectable]) + "," + append + ")");
    },
    /**
     * @description 接收到 web-view 消息
     */
    _onMessage(e) {
      const message = e.detail.data[0];
      switch (message.action) {
        case "onJSBridgeReady":
          this._ready = true;
          if (this.nodes) {
            this._set(this.nodes);
          }
          break;
        case "onLoad":
          this.height = message.height;
          this._hook("onLoad");
          this.$emit("load");
          break;
        case "onReady":
          this.getRect().then((res) => {
            this.$emit("ready", res);
          }).catch(() => {
            this.$emit("ready", {});
          });
          break;
        case "onHeightChange":
          this.height = message.height;
          break;
        case "onImgTap":
          this.$emit("imgtap", message.attrs);
          if (this.previewImg) {
            uni.previewImage({
              current: parseInt(message.attrs.i),
              urls: this.imgList
            });
          }
          break;
        case "onLinkTap": {
          const href = message.attrs.href;
          this.$emit("linktap", message.attrs);
          if (href) {
            if (href[0] === "#") {
              if (this.useAnchor) {
                dom.scrollToElement(this.$refs.web, {
                  offset: message.offset
                });
              }
            } else if (href.includes("://")) {
              if (this.copyLink) {
                plus.runtime.openWeb(href);
              }
            } else {
              uni.navigateTo({
                url: href,
                fail() {
                  uni.switchTab({
                    url: href
                  });
                }
              });
            }
          }
          break;
        }
        case "onPlay":
          this.$emit("play");
          break;
        case "getOffset":
          if (typeof message.offset === "number") {
            dom.scrollToElement(this.$refs.web, {
              offset: message.offset + this._navigateTo.offset
            });
            this._navigateTo.resolve();
          } else {
            this._navigateTo.reject(Error("Label not found"));
          }
          break;
        case "onClick":
          this.$emit("tap");
          this.$emit("click");
          break;
        case "onError":
          this.$emit("error", {
            source: message.source,
            attrs: message.attrs
          });
      }
    }
    // #endif
  }
};
import { renderSlot as _renderSlot, createCommentVNode as _createCommentVNode, resolveComponent as _resolveComponent, createVNode as _createVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, normalizeStyle as _normalizeStyle, normalizeClass as _normalizeClass } from "vue";
function __vue_render__(_ctx, _cache) {
  const _component_node = _resolveComponent("node");
  const _component_web_view = _resolveComponent("web-view");
  return _openBlock(), _createElementBlock(
    "view",
    {
      id: "_root",
      class: _normalizeClass((_ctx.selectable ? "_select " : "") + "_root"),
      style: _normalizeStyle(_ctx.containerStyle)
    },
    [
      !_ctx.nodes[0] ? _renderSlot(_ctx.$slots, "default", { key: 0 }) : (_openBlock(), _createElementBlock(
        _Fragment,
        { key: 1 },
        [
          _createCommentVNode(" #ifndef APP-PLUS-NVUE "),
          _createVNode(_component_node, {
            childs: _ctx.nodes,
            opts: [_ctx.lazyLoad, _ctx.loadingImg, _ctx.errorImg, _ctx.showImgMenu, _ctx.selectable],
            name: "span"
          }, null, 8, ["childs", "opts"])
        ],
        2112
        /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */
      )),
      _createCommentVNode(" #endif "),
      _createCommentVNode(" #ifdef APP-PLUS-NVUE "),
      _createVNode(_component_web_view, {
        ref: "web",
        src: "/uni_modules/mp-html/static/app-plus/mp-html/local.html",
        style: _normalizeStyle("margin-top:-2px;height:" + _ctx.height + "px"),
        onOnPostMessage: _ctx._onMessage
      }, null, 8, ["style", "onOnPostMessage"]),
      _createCommentVNode(" #endif ")
    ],
    6
    /* CLASS, STYLE */
  );
}
__vue_sfc__.render = __vue_render__;
var stdin_default = __vue_sfc__;
export {
  stdin_default as default
};
